//
//  ItemAddInformationController.swift
//  Fancyswap
//
//  Created by Jonathan Muschalle on 2015-03-21.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//

import UIKit

class ItemAddInformationController: UITableViewController {
    
    let ITEM_ADD_STATUS_SUCCESS = 1
    
    @IBOutlet weak var itemName: UITextField!
    @IBOutlet weak var itemBrand: UITextField!
    @IBOutlet weak var itemSize: UITextField!
    @IBOutlet weak var itemCondition: UISegmentedControl!
    @IBOutlet weak var itemPrice: UITextField!
    @IBOutlet weak var itemDescription: UITextView!
    @IBOutlet weak var itemCoins: UILabel!
    
    @IBOutlet weak var loadingCell: UITableViewCell!
    
    var itemConditionFinal = "3"
    
    func submitItem(item: ItemToAdd) {
        loadingCell.hidden = false
        self.tableView.contentOffset = CGPointMake(0, 0 - self.tableView.contentInset.top)
//        fancy_token = "b53f8e9c2960eb726ac4f7acf190123c280e6240c"
        Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization":fancy_token]
        request(
            .POST,
            "http://api.fancyswap.com/rest/1.0/item",
            parameters: item.toJsonParameter(),
            encoding: ParameterEncoding.JSON)
        .responseJSON {
            (request, data, JSON_REPONSE, error) in
            let jsonResult: AnyObject = JSON_REPONSE!
            
            if let status = jsonResult["status"] as? Int {
                if(status == self.ITEM_ADD_STATUS_SUCCESS) {
                    pictureListToAdd.clear()
                    self.loadingCell.hidden = true
                    
                    var storyboard = UIStoryboard(name: "MyItems", bundle: nil)
                    var controller = storyboard.instantiateViewControllerWithIdentifier("myItems") as UIViewController
                    self.presentViewController(controller, animated: true, completion: nil)
                    
                } else {
                    let message = jsonResult["message"] as? String
                    self.showMessage("Erreur :\(message)", title: "Erreur")
                    self.loadingCell.hidden = true
                }
            } else {
                self.showMessage("Erreur :\(JSON_REPONSE)", title: "Erreur")
            }
            
        }
    }
    
    ///Show message box with ok button
    func showMessage(msg: String, title: String)
    {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.ActionSheet)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:
            {
                action -> Void in

            }
            ))
        
        presentViewController(alert, animated: true) { () -> Void in }
        
    }
    
    @IBAction func submitItem(sender: AnyObject) {
        var item = ItemToAdd.createItem(
            itemName.text,
            brand: itemBrand.text,
            price: itemPrice.text,
            description: itemDescription.text,
            size: itemSize.text,
            condition: itemConditionFinal,
            coins: itemCoins.text!,
            pictures: pictureListToAdd)
        submitItem(item)
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        var tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "closeKeyboard")
        self.view.addGestureRecognizer(tap)
    }

    @IBAction func onPriceChange(sender: AnyObject) {
        var coefficient:CGFloat = 0.5
        switch itemCondition.selectedSegmentIndex {
            case 0:
                coefficient = 1
                itemConditionFinal = "1"
            case 1:
                coefficient = 0.8
                itemConditionFinal = "2"
            case 2:
                coefficient = 0.5
                itemConditionFinal = "3"
            default:
                coefficient = 0.5
                itemConditionFinal = "3"
        }
        var originalPriceChanged:Int = 0
        if(!itemPrice.text.isEmpty) {
            originalPriceChanged = itemPrice.text.toInt()!
        }
        var swapcoins = CGFloat(originalPriceChanged) * 13 * coefficient
        itemCoins.text = "\(ceil(swapcoins))"
        
    }
    
    func closeKeyboard() {
        self.view.endEditing(true)
        
    }
}
